package com.sosee.cgfw.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Debug;
import android.text.format.Formatter;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

/**
 * Created by Thinkpad on 2016/3/30.
 * //记录apk错误信息 并上传至服务器 工具类
 */
public class ErrorUtils {
    private static Activity activity;
    //创建 日志数据库 字段 ：手机型号 内存 可用内存 系统版本 apk版本 屏幕尺寸 cpu主频 异常信息 错误类 错误方法 异常抛出地点

    private static ActivityManager mActivityManager;
    //获取apk运行时所占用设备的内存
    public static String getApkUseMemory(Context context) {
        String size="";

        mActivityManager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);

        //获得系统里正在运行的所有进程
        int mPid=android.os.Process.myPid ();

        List<ActivityManager.RunningAppProcessInfo> runningAppProcessesList = mActivityManager.getRunningAppProcesses();

        for (ActivityManager.RunningAppProcessInfo runningAppProcessInfo : runningAppProcessesList) {          // 进程ID号

            int pid = runningAppProcessInfo.pid;

            // 用户ID          i

            int uid = runningAppProcessInfo.uid;

            // 进程名

            String processName = runningAppProcessInfo.processName;

            // 占用的内存

            int[] pids = new int[] {pid};

            Debug.MemoryInfo[] memoryInfo =mActivityManager.getProcessMemoryInfo(pids);

            int memorySize = memoryInfo[0].dalvikPrivateDirty;
            if(mPid==pid){
                size= Formatter.formatFileSize(activity.getBaseContext(),memorySize);
            }
            System.out.println("processName="+processName+",pid="+pid+",uid="+uid+",memorySize="+memorySize+"kb");
        }
        return size;
    }


    //将错误信息写入文件
    public static void write(String err){
        File file=new File(Constans.PATH_BASE+"err.txt");
        FileOutputStream fos=null;
        try {
            fos=new FileOutputStream(file);
            fos.write(err.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
                try {
                    if (fos!=null)
                        fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
    }


    //将错误信息从文件中读出
    public static String readErrLog(){
        String err="";
        FileInputStream fis=null;
        BufferedInputStream reader=null;
        StringBuffer sb=new StringBuffer();
        try {
            fis=new FileInputStream(new File(Constans.PATH_BASE+"err.txt"));
            reader=new BufferedInputStream(fis);
            byte[] bys = new byte[1024];
            int len = 0;
            while ((len = reader.read(bys)) != -1) {
                System.out.print(new String(bys, 0, len));
                sb.append(bys.toString());
            }
            err=sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                if(fis!=null)
                    fis.close();
                if (reader!=null)
                    reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return err;
    }


    //上传信息
    public static void update(String str){
        HttpUtils httpUtils=new HttpUtils();
        RequestParams params=new RequestParams();
        httpUtils.send(HttpRequest.HttpMethod.POST, "",params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String status=responseInfo.result;
                if("success".equals(status)){

                }else{

                }
            }

            @Override
            public void onFailure(HttpException e, String s) {

            }
        });
    }


    //写入本地文件 记录日志是否上传成功
    private static SharedPreferences sp;
    public static void writeSp(String key,String value){
        sp=activity.getSharedPreferences("logcat",Context.MODE_PRIVATE);
        SharedPreferences.Editor editor=sp.edit();
        editor.putString(key,value);
        editor.commit();
    }

    //读取本地日志文件 判断现有日志上传状态
    public static String getSpt(String key){
        String str="";
        sp=activity.getSharedPreferences("logcat",Context.MODE_PRIVATE);
        str=sp.getString(key,"");
        return str;
    }


}
